package com.qr.backend.config;

import com.alibaba.fastjson.JSONObject;
import com.qr.backend.entity.RestInfo;
import com.qr.backend.service.AuthorizeService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author : jinxiaobo
 * @date : 2023年12月18日 17:11:40
 * @description : Security配置，SpringBoot3.0的配置
 */
@Configuration
//开启WebSecurity功能
@EnableWebSecurity
public class SecurityConfiguration {

    //注入认证服务器
    @Resource
    private AuthorizeService authorizeService;

    //导入数据源
    @Resource
    private DataSource dataSource;

    /**
     * 登入和登出的基本配置
     * @param httpSecurity
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .authorizeHttpRequests()
                //所有获取校验相关的接口放行,允许所有人访问
                .requestMatchers("/api/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/api/auth/login")
                .successHandler(this::onAuthenticationSuccess)
                .failureHandler(this::onAuthenticationFailure)
                .and()
                .logout()
                .logoutUrl("/api/auth/logout")
                .logoutSuccessHandler(this::onAuthenticationSuccess)
                .and()
                //记住我
                .rememberMe()
                .rememberMeParameter("remember")//设置前端传递过来记住我的参数,默认是一个remember-me
                .tokenRepository(tokenRepository())
                .tokenValiditySeconds(3600*24*7)//设置token的有效时间,设置为三天时间
                .and()
                //指定认证服务,或者注释掉这行,使用下面的authenticationManager方法进行注入一个AuthenticationManager也可以
                .userDetailsService(authorizeService)
                .csrf().disable()
                //配置跨域
                .cors()
                .configurationSource(configurationSource())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(this::onAuthenticationFailure)
                .and()
                .build();
    }


    /**
     * 记住我功能,持久化token仓库
     * @return
     */
    @Bean
    public PersistentTokenRepository tokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //一开始的时候创建这张表,之后就可以改为false
        jdbcTokenRepository.setCreateTableOnStartup(false);
        return jdbcTokenRepository;
    }


    /**
     * 配置跨域
     * @return
     */
    private CorsConfigurationSource configurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //这个表示允许所有的跨域请求，一般写具体的地址,比如:lcoalhost:8080
        corsConfiguration.addAllowedOriginPattern("*");
        //设置为允许携带cookie
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //所有的请求都走这个跨域配置
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }


    /*@Bean
    public AuthenticationManager authenticationManager(HttpSecurity security) throws Exception {
        return security.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(authorizeService)
                .and().build();
    }*/

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 登入成功的处理,前后端分离,登入成功后要返回给前端一个数据
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /*response.setCharacterEncoding("utf-8");
        response.getWriter().write("登入成功");*/
        //将成功的信息转换为一个JSON对象进行返回
        response.setCharacterEncoding("utf-8");
        if (request.getRequestURI().endsWith("login"))
            response.getWriter().write(JSONObject.toJSONString(RestInfo.success("登入成功")));
        else if (request.getRequestURI().endsWith("logout"))
            response.getWriter().write(JSONObject.toJSONString(RestInfo.success("退出登入")));
    }


    /**
     * 登入失败处理逻辑
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSONObject.toJSONString(RestInfo.failure(401,exception.getMessage())));
    }

    /**
     * 访问其他资源异常
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSONObject.toJSONString(RestInfo.failure(401,authException.getMessage())));
    }

}
